package com.mowanka.mokeng.viewmodel.request

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mowanka.mokeng.app.network.apiService
import com.mowanka.mokeng.data.model.bean.FloorResponse
import com.mowanka.mokeng.data.model.bean.NewsInfo
import com.mowanka.mokeng.data.model.bean.PopularSelectionBean
import com.mowanka.mokeng.data.model.bean.UserPlayingBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.network.AppException
import me.hgj.jetpackmvvm.state.ResultState

class RequestStoreViewModel : BaseViewModel() {

    var floorResponse = MutableLiveData<ResultState<ArrayList<FloorResponse>>>()
    var popResponse = MutableLiveData<ResultState<PopularSelectionBean>>()
    var userPlayResponse = MutableLiveData<ResultState<UserPlayingBean>>()

    fun floor() {
        request({ apiService.floor() }, floorResponse)
    }

    fun request(floorInfo: FloorResponse) {
        viewModelScope.launch {
            floorInfo.floorList.forEach {
                when (it.interfaceType) {
                    16 -> {
                        val result = withContext(Dispatchers.IO) { apiService.popList() }
                        popResponse.value = when {
                            result.isSucces() -> ResultState.onAppSuccess(
                                PopularSelectionBean(
                                    it.title,
                                    result.getResponseData()
                                )
                            )
                            else -> ResultState.onAppError(AppException(result.getResponseCode(), result.getResponseMsg()))
                        }
                    }
                    17 -> {
                        val result = withContext(Dispatchers.IO) { apiService.userPlayList() }
                        userPlayResponse.value = when {
                            result.isSucces() -> ResultState.onAppSuccess(UserPlayingBean(it.title, result.getResponseData()))
                            else -> ResultState.onAppError(AppException(result.getResponseCode(), result.getResponseMsg()))
                        }
                    }
                }
            }
        }
    }

    private var pageNo = 1
    private var pageSize = 10
    var productList = MutableLiveData<ResultState<ArrayList<NewsInfo>>>()
    fun getProductList(map: MutableMap<String, Any>, pageNo: Int) {
        map["pageNumber"] = pageNo
        map["pageSize"] = pageSize
        request({
            delay(1000)
            apiService.recommendList(map)
        }, productList)
    }
}